package com.aiwei.tdjk.controller.sys;

import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.controller.BaseController;
import com.aiwei.tdjk.dto.request.GetAuthPagerRequest;
import com.aiwei.tdjk.entity.Auth;
import com.aiwei.tdjk.entity.Role;
import com.aiwei.tdjk.enums.AuthType;
import com.aiwei.tdjk.service.AuthService;
import com.aiwei.tdjk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>User: yanfeng
 * <p>Version: 1.0
 */
@Controller
@RequestMapping(value = "/admin/sys/auth")
public class AuthController extends BaseController<Auth> {

    @Autowired
    private AuthService authService;

    @Autowired
    private RoleService roleService;


    protected void setCommonData(Model model) {
        model.addAttribute("types", AuthType.values());
        model.addAttribute("roles", roleService.list());
    }

    @RequestMapping(value = {""}, method = RequestMethod.GET)
    public String list(GetAuthPagerRequest request, Model model) {
        if (request.getType() == null) {
            request.setType(AuthType.user.name());
        }
        model.addAttribute("type", request.getType());
        model.addAttribute("page", authService.find(request));
        setCommonData(model);
        return viewName("list");
    }


    @RequestMapping(value = "{type}/create", method = RequestMethod.GET)
    public String showCreateFormWithType(@PathVariable("type") AuthType type, Model model) {
        Auth auth = new Auth();
        auth.setType(type.name());
        model.addAttribute("m", auth);
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "新增");

        //所有的角色列表
        List<Role> roles = roleService.list();
        //未选择的角色列表
        model.addAttribute("noSelectedRoles", roles);
        model.addAttribute("selectedRoles", null);
        model.addAttribute("type", type);

        //已选择的角色列表
        return viewName("editForm");
    }


    @RequestMapping(value = "{type}/create", method = RequestMethod.POST)
    public String createWithType(
            Model model,
            @RequestParam(value = "userIds", required = false) Long[] userIds,
            @RequestParam(value = "groupIds", required = false) Long[] groupIds,
            @RequestParam(value = "organizationIds", required = false) Long[] organizationIds,
            @RequestParam(value = "jobIds", required = false) Long[][] jobIds,
            @Valid @ModelAttribute("m") Auth auth, BindingResult result,
            RedirectAttributes redirectAttributes) {
        if (hasError(result)) {
            return showCreateFormWithType(null, model);
        }

        if (auth.getType().equals(AuthType.user.name())) {
            authService.addUserAuth(userIds, auth);
        } else if (auth.getType().equals(AuthType.user_group.name()) || auth.getType().equals(AuthType.organization_group.name())) {
            authService.addGroupAuth(groupIds, auth);
        } else if (auth.getType().equals(AuthType.organization_job.name())) {
            authService.addOrganizationJobAuth(organizationIds, jobIds, auth);
        }
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "新增成功");
        return redirectToUrl("");
    }


    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "修改");
        Auth auth = authService.get(id);
        model.addAttribute("m", auth);
        model.addAttribute("type", AuthType.getValue(auth.getType()));
        // 去除已经有的
        List<Role> selectedRoles = roleService.getByRoleIds(auth.getRoleIds());
        List<Role> noSelectedRoles = roleService.list();

        List<Role> delList = new ArrayList();//用来装需要删除的元素
        if(selectedRoles!=null && selectedRoles.size()>0){
            for (Role role : noSelectedRoles) {
                for (Role selectedRole : selectedRoles) {
                    if (role.getId().equals(selectedRole.getId())) {
                        delList.add(role);
//                    noSelectedRoles.remove(role);
                    }
                }

            }
        }

        noSelectedRoles.removeAll(delList);
        model.addAttribute("noSelectedRoles",noSelectedRoles);
        model.addAttribute("selectedRoles",selectedRoles);
        return viewName("editForm");
    }


    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String update(
            Model model, @Valid @ModelAttribute("m") Auth m, BindingResult result,
            RedirectAttributes redirectAttributes) {

        if (hasError(result)) {
            return showUpdateForm(m.getId(), model);
        }
        authService.update(m);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "修改成功");
        return redirectToUrl("");
    }


    @RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
    public String delete(
            @PathVariable("id") long id,
            RedirectAttributes redirectAttributes) {

        authService.delete(id);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("");
    }

    @RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public String deleteInBatch(
            @RequestParam(value = "ids", required = false) Long[] ids,
            RedirectAttributes redirectAttributes) {

        authService.delete(ids);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("");
    }


}
